﻿using System.IO;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace WickedFlame.Util.Actions
{
    /// <summary>
    /// This class converts a image without alpha chanel to a image with alpha chanel (Pbgra32)
    /// This has to be done so that the image can be cut with the cut-tool
    /// </summary>
    public class ConvertImageToPbgra32Action
    {
        public BitmapImage ConvertBitmapFormat(BitmapSource image)
        {
            //if (image is InteropBitmap)
            //{
            //    // works with this ugly hack!
            //    image = GetImage();
            //}

            //var fcb = new FormatConvertedBitmap(image, PixelFormats.Bgra32, null, 0);

            var fcb = new FormatConvertedBitmap();
            fcb.BeginInit();
            fcb.Source = image;
            // Set the new format to Pbgra32 -- Gray32Float (grayscale).
            fcb.DestinationFormat = PixelFormats.Pbgra32; //Bgra32;
            fcb.EndInit();

            return SourceToImage(fcb);
        }

        public BitmapImage ConvertBitmapFormat(RenderTargetBitmap renderTarget)
        {
			using (var strm = new MemoryStream())
			{

				var encoder = new PngBitmapEncoder
				{
					Interlace = PngInterlaceOption.On
				};
				encoder.Frames.Add(BitmapFrame.Create(renderTarget));
				encoder.Save(strm);
				strm.Seek(0, SeekOrigin.Begin);

				var image = new BitmapImage();
				image.BeginInit();
				image.CacheOption = BitmapCacheOption.OnLoad;
				image.StreamSource = strm;
				image.EndInit();

				//remove all references
				image.StreamSource.Dispose();

				return image;
			}
        }

        public static BitmapImage SourceToImage(BitmapSource source)
        {
			using (var strm = new MemoryStream())
			{

				var encoder = new PngBitmapEncoder
				{
					Interlace = PngInterlaceOption.On
				};
				encoder.Frames.Add(BitmapFrame.Create(source));
				encoder.Save(strm);
				strm.Seek(0, SeekOrigin.Begin);

				var img = new BitmapImage();
				img.BeginInit();
				img.CacheOption = BitmapCacheOption.OnLoad;
				img.StreamSource = strm;
				img.EndInit();

				return img;
			}
        }

        //private BitmapSource GetImage()
        //{
        //    System.Drawing.Bitmap img = (System.Drawing.Bitmap)System.Windows.Forms.Clipboard.GetImage();
        //    BitmapSource image = CreateBitmap(img.GetHbitmap());
        //    return image;
        //}

        //internal BitmapSource CreateBitmap(IntPtr handle)
        //{
        //    return System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
        //        handle, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
        //}
    }
}
